import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getBanners, getNewAlbum, getRecommend } from "../service/recommend";

// 首页轮播
export const fetchBannerDataAction = createAsyncThunk("banners", async (arg, { dispatch, getState }) => {
	const res = await getBanners();
	// 方式一使用  extraReducers 监听
	// return res;
	// 方式二 通过despatch
	dispatch(changeBannersAction(res.banners));
});
// 热门推荐
export const fetchHotRecommend = createAsyncThunk("hotRecommend", async (arg, { dispatch }) => {
	const res = await getRecommend(10);
	dispatch(changeHotRecommendAction(res.result));
});
// 新碟上架
export const fetchGetNewAlbum = createAsyncThunk("newaAblum", async (arg, { dispatch }) => {
	const res = await getNewAlbum();
	dispatch(changeNewAlbumAction(res.albums));
});
interface IRecommendState {
	banners: any[];
	hotRecommends: any[];
	newAlbums: any[];
}

const initialState: IRecommendState = {
	banners: [],
	hotRecommends: [],
	newAlbums: [],
};
const recommendSlice = createSlice({
	name: "recommend",
	initialState,
	reducers: {
		changeBannersAction(state, { payload }) {
			state.banners = payload;
		},
		changeHotRecommendAction(state, { payload }) {
			state.hotRecommends = payload;
		},
		changeNewAlbumAction(state, { payload }) {
			state.newAlbums = payload;
		},
	},
	/* 	extraReducers: (buildes) => {
		buildes
			.addCase(fetchBannerDataAction.pending, (state, action) => {
				console.log("action", state, action);
			})
			.addCase(fetchBannerDataAction.fulfilled, (state, { payload }) => {
				console.log("获取结果", state);
				console.log("获取结果1", payload);
				state.banners = payload?.banners;
			})
			.addCase(fetchBannerDataAction.rejected, (state, action) => {
				console.log("报错", state, action);
			});
	}, */
});

export const { changeBannersAction, changeHotRecommendAction, changeNewAlbumAction } = recommendSlice.actions;

export default recommendSlice.reducer;
